from machine import Pin
from lib.api import iot
from lib.sensors.rtc import ds3231
from lib.config.index import sensor_config
import asyncio

__service__ = "person sensor"
__description__ = "upload person data to iot platform"

ds = None
pin = None
old_has_person = 0


def init():
    global ds, pin
    config = sensor_config.get_sensor("ds3231")
    scl_pin = config["scl"]
    sda_pin = config["sda"]
    print("ds3231 config:", config)
    ds = ds3231.DS3231(gpio_scl=scl_pin, gpio_sda=sda_pin)
    pin = Pin(10, Pin.IN)


async def run():
    global ds, pin, old_has_person
    while True:
        has_person = pin.value()
        year, month, day, hour, minute, second = ds.DateTime()
        temp = ds.Temperature()
        year = f"20{year}"
        month = "{:02}".format(month)
        day = "{:02}".format(day)
        hour = "{:02}".format(hour)
        minute = "{:02}".format(minute)
        second = "{:02}".format(second)
        t = f"{year}-{month}-{day} {hour}:{minute}:{second}"
        print(f"temp: {temp}°C")

        try:
            if has_person != old_has_person:
                iot.upload_data(
                    f"{has_person},{temp},{t}",
                    "Tiot_bba1471x",
                    {"has_person": has_person, "ds3231": {"rtc": t, "temp": temp}},
                )
                old_has_person = has_person
            print(has_person)
        except Exception as e:
            print(e)

        await asyncio.sleep(8)
